What is @svgr/plugin-jsx?
@svgr/plugin-jsx is a plugin for SVGR (SVG to React) that transforms SVG files into JSX code. This allows developers to use SVGs as React components, making it easier to integrate and manipulate SVG graphics within React applications.
What are @svgr/plugin-jsx's main functionalities?
Basic SVG to JSX Transformation
Transforms a basic SVG string into JSX code that can be used as a React component.
const svgCode = '<svg><circle cx="50" cy="50" r="40" /></svg>';
const jsxCode = transform(svgCode, { plugins: ['@svgr/plugin-jsx'] });
console.log(jsxCode);
Customizing JSX Output
Allows customization of the JSX output using Babel presets and other configurations.
const svgCode = '<svg><circle cx="50" cy="50" r="40" /></svg>';
const jsxCode = transform(svgCode, { plugins: ['@svgr/plugin-jsx'], jsx: { babelConfig: { presets: ['@babel/preset-react'] } } });
console.log(jsxCode);
Adding Props to SVG Components
Automatically adds props to the SVG components, making them more flexible and reusable.
const svgCode = '<svg><circle cx="50" cy="50" r="40" /></svg>';
const jsxCode = transform(svgCode, { plugins: ['@svgr/plugin-jsx'], jsx: { expandProps: 'start' } });
console.log(jsxCode);
Other packages similar to @svgr/plugin-jsx
react-svg
react-svg is a library that allows you to import SVG files as React components. It provides similar functionality to @svgr/plugin-jsx but focuses more on runtime usage rather than build-time transformations.
svg-react-loader
svg-react-loader is a Webpack loader that transforms SVG files into React components. It offers similar capabilities to @svgr/plugin-jsx but is specifically designed to work within the Webpack ecosystem.
react-inlinesvg
react-inlinesvg is a React component that loads and injects SVGs inline. Unlike @svgr/plugin-jsx, it focuses on runtime loading and rendering of SVGs rather than transforming them into JSX at build time.
@svgr/plugin-jsx
Transforms SVG into JSX.
Install
npm install --save-dev @svgr/plugin-jsx
Usage
.svgrrc
{
"plugins": ["@svgr/plugin-jsx"]
}
How does it work?
@svgr/plugin-jsx
consists in three phases:
Applying custom transformations
You can extend the Babel config applied in this plugin using jsx.babelConfig
config path:
module.exports = {
jsx: {
babelConfig: {
plugins: [
[
'@svgr/babel-plugin-remove-jsx-attribute',
{
elements: ['svg'],
attributes: ['id'],
},
],
],
},
},
}
Several Babel plugins are available:
If you want to create your own, reading Babel Handbook is a good start!
License
MIT